/**
 * Author:  LiShibin.
 * Date:    2016/12/12.
 * File：   .
 */
let HmacMD5 = require('crypto-js/hmac-md5.js')

/***
 * 获取签名
 * @param sec 是否加密
 * @param url 请求地址
 * @param ak accessTokenKey
 * @param at accessToken
 * @param ct 参数
 * @return {Promise.<*>}
 * 说明：async函数返回的是promise对象
 */
async function getSign (ak, at, ct, sec, url, clientId) {
  let pa = at + (sec ? [clientId, ak, ct, sec, url] : [clientId, ak, ct])
  .sort().join('').replace(/\t|\r|\n/g, '') + at

  let sign
  try {
    sign = HmacMD5(pa, at).toString().toUpperCase()
  } catch (e) {
    console.log('签名错误')
    console.log(e)
  }
  return sign
}

/***
 * 获取头部
 * @param type
 * @param url
 * @param data
 * @return {Promise.<{Content-Type: string, ehome-head-params: string}>}
 * 说明：async函数返回的是promise对象
 */
async function getHead (type, url, data) {
  let clientId = window.localStorage.getItem('clientId') || '2E7966B47EA04112BBC03F3B9992E6F7'
  let args = []
  let ak = window.localStorage.getItem('accessTokenKey') || ''
  let at = window.localStorage.getItem('accessToken') || ''
  let userId = window.localStorage.getItem('userId') || 'U4E2C821DF43E4ED7B1BE3384BC4A169D'
  let ct = JSON.stringify(data)
  // console.log('uid', uid)
  let sec = 'F'
  let sign
  switch (type) {
    case 'oauth':
      args.push(clientId)
      args.push(url)
      args.push('')
      break
    case 'inner':
      args.push(userId)
      args.push(url)
      args.push('')
      break
    case 'outer':
    case 'workflow':
    case 'outerOauth':
      sign = await getSign(ak, at, ct, sec, url, clientId)
      args.push(clientId)
      args.push(ak)
      args.push(sign)
      args.push(sec)
      args.push(url)
      args.push('')
      break
    case 'swagger':
      sign = await getSign(ak, at, ct, clientId)
      args.push(clientId)
      args.push(ak)
      args.push(sign)
      args.push('')
      let header = {
        'Accept': '*/*',
        'yongtai-shengtai-head-params': args.join(';')
      }
    return header
    case 'swaggerTest':
    sign = await getSign(ak, at, ct, clientId)
    args.push(clientId)
    args.push(ak)
    args.push(sign)
    args.push('')
    header = {
      'Accept': '*/*',
      'yongtai-shengtai-head-params': args.join(';')
    }
    return header
  }
  let header = {
    'Content-Type': 'application/octet-stream',
    'ehome-head-params': args.join(';')
  }
  return header
}

export default getHead
